//
//  HSHttpCacheDB.m
//  AFNetworking
//
//  Created by huang on 2018/8/3.
//

#import "HSHttpCacheDB.h"
#import "FMDB.h"

static FMDatabaseQueue *_dbQueue;
static NSString *_tableName = @"tb_Cache";

@implementation HSHttpCacheDB

+ (instancetype)sharedManager
{
    NSString *path = [HSHttpCacheDB dBPath];
    static HSHttpCacheDB *httpCacheDB = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL fileExists = [fileManager fileExistsAtPath:path];
        if (!fileExists) {
            [fileManager createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
        }
        _dbQueue = [[FMDatabaseQueue alloc] initWithPath:path];
        httpCacheDB = [[HSHttpCacheDB alloc] init];
        [_dbQueue inDatabase:^(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT,cache_data blob not null,cache_key text)",_tableName];
            if ([db executeUpdate:sql]) {
                NSLog(@"创建表成功");
            } else {
                NSLog(@"创建失败");
            }
        }];
    });
    return httpCacheDB;
}

#pragma mark 缓存数据到数据库
- (void)insertItem:(id)item cacheKey:(NSString *)cacheKey
{
    [_dbQueue inDatabase:^(FMDatabase *db) {
        if ([db open]) {
            NSData *cacheData = [NSKeyedArchiver archivedDataWithRootObject:item];
            NSString *sql = [NSString stringWithFormat:@"REPLACE INTO %@ (cache_data,cache_key) VALUES (%@,%@)",_tableName,cacheData,cacheKey];
            BOOL ret = [db executeUpdate:sql];
            if (ret == YES) {
                NSLog(@"插入成功");
            }else {
                NSLog(@"插入失败");
            }
            
            [db close];
        }
    }];
}

#pragma mark 通过缓存的key来获取对应的数据
- (id)itemWithCacheKey:(NSString *)cacheKey
{
    __block id obj = nil;
    [_dbQueue inDatabase:^(FMDatabase *db) {
        if ([db open] && cacheKey) {
            FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ WHERE cache_key = %@",_tableName,cacheKey]];
            while ([rs next]) {
                NSData *data = [rs dataForColumn:@"cache_data"];
                obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                break;
            }
            
            [db close];
        }
    }];
    
    return obj;
}

#pragma mark 清空所有缓存数据
- (void)clearAll
{
    [_dbQueue inDatabase:^(FMDatabase *db) {
        if ([db open]) {

            NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",_tableName];
            BOOL ret = [db executeUpdate:sql];
            if (ret == YES) {
                NSLog(@"删除成功");
            }else {
                NSLog(@"删除失败");
            }
            
            [db close];
        }
    }];
}

#pragma mark - 数据库路径
+ (NSString *)dBPath
{
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *dbPath = [documentPath stringByAppendingPathComponent:@"httpCache.db"];
    return dbPath;
}

@end
